package com.blue.http.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.blue.http.config.ErrorConfig;
import com.blue.http.message.HttpRequest;
import com.blue.http.message.HttpResponse;


/**
 * HTTP日志工具类
 * 
 * @author zhengj
 * @since 1.0 2016年10月10日
 */
public class HttpLogUtil
{
	private static Logger logger = LoggerFactory.getLogger(HttpLogUtil.class);
	
	private HttpLogUtil()
	{
	}
	
	public static void log(HttpRequest request, String content)
	{
		long used = System.currentTimeMillis() - request.getStart();
		String get = request.getQueryString();
		String post = getPost(request);
		logger.info("url: {}, method: {}, result: 成功, used: {}ms\nGET参数: {}\nPOST参数: {}\n返回: {}", request.getUrl(), request.getHttpMethod().name(),
				used, get, post, content);
	}
	
	public static void log(HttpRequest request, HttpResponse response, Exception e)
	{
		long used = System.currentTimeMillis() - request.getStart();
		String get = request.getQueryString();
		String post = getPost(request);
		
		if (response.getCode() == ErrorConfig.ERROR)
		{
			logger.info("url: {}, method: {}, result: 失败, used: {}ms\nGET参数: {}\nPOST参数: {}\ncode: {}, msg: {}",
					request.getUrl(), request.getHttpMethod().name(), 
					used, get, post, response.getCode(), response.getMsg());
			logger.error("异常: ", e);
		}
		else if (response.getCode() == ErrorConfig.PARAM)
		{
			logger.info("url: {}, method: {}, result: 失败, used: {}ms\nGET参数: {}\nPOST参数: {}\ncode: {}, msg: {}, extmsg: {}",
					request.getUrl(), request.getHttpMethod().name(), 
					used, get, post, response.getCode(), response.getMsg(), response.getExtmsg());
		}
		else
		{
			logger.info("url: {}, method: {}, result: 失败, used: {}ms\nGET参数: {}\nPOST参数: {}\ncode: {}, msg: {}",
					request.getUrl(), request.getHttpMethod().name(), 
					used, get, post, response.getCode(), response.getMsg());
		}
	}
	
	private static String getPost(HttpRequest request)
	{
		if (request.getContent() != null && !request.getContent().isEmpty())
			return request.getContent();
		
		StringBuilder post = new StringBuilder(64);
		post.append(request.getPostMap()).append("\n").append(request.getFileMap());
		return post.toString();
	}
	
}
